import { outLogin } from '@/services/ant-design-pro/api';
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Spin,message } from 'antd';
import { createStyles } from 'antd-style';
import { stringify } from 'querystring';
import React, { useCallback } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};
// 头像下拉菜单
export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUserInfo } = initialState || {};
  return <span className="anticon">{currentUserInfo?.loginname}</span>;
};

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
  };
});

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu, children }) => {
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    const msg = await outLogin();
    if (msg.status === 200) {
      // 清除用户信息
      localStorage.removeItem('userInfo');
      const { search, pathname } = window.location;
      const urlParams = new URL(window.location.href).searchParams;
      /** 此方法会跳转到 redirect 参数所在的位置 */
      const redirect = urlParams.get('redirect');
      message.success(msg.data);
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: pathname + search,
          }),
        });
      }
    }

  };
  const { styles } = useStyles();

  const { initialState, setInitialState } = useModel('@@initialState');
  //退出登录应该设置 initialState为空
  const onMenuClick = useCallback(
    (event: any) => {
      const { key } = event;
      if (key === 'logout') {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUserInfo: undefined }));
        });
        loginOut();
        return;
      }
      // 点击其他菜单项，跳转到相应的页面
      history.push(`/account/${key}`);
    },
    [setInitialState],
  );

  const loading = (
    <span className={styles.action}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  // 如果 initialState 为空，则渲染 loading 组件
  if (!initialState) {
    return loading;
  }
  //
  const { currentUserInfo } = initialState;

  // 如果 currentUserInfo 为空，则渲染 loading 组件
  if (!currentUserInfo || !currentUserInfo.loginname) {
    return loading;
  }

  //如果 menu 为真，menuItems 数组将包含三个菜单项（个人中心、个人设置和一个分隔符），以及一个始终存在的退出登录项。
  //如果 menu 为假，menuItems 数组将只包含退出登录项。
  const menuItems = [
    ...(menu ? [
      {
        key: 'center',
        icon: <UserOutlined />,
        label: '个人中心',
      },
      {
        key: 'settings',
        icon: <SettingOutlined />,
        label: '个人设置',
      },
      {
        type: 'divider' as const,
      },
    ]
      : []),
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      {children}
    </HeaderDropdown>
  );
};
